﻿using HJMinimally.AutoMapper;
using HJMinimally.Cache.Redis;
using HJMinimally.Minio.IServices;
using HJMinimally.Minio.Model;
using HJMinimally.Minio.ViewModel.Req;
using HJMinimally.Repository.SqlSugar;
using HJMinimally.Utility;
using HJMinimally.Utility.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HJMinimally.Minio.Services
{
    /// <summary>
    /// 系统上传配置服务
    /// </summary>
    public class FileUploadConfigService: IFileUploadConfigService
    {
        private readonly string cacheKey = "hjminimally_minio_fileuploadconfig";
        private readonly string fileFormatCacheKey = "hjminimally_minio_fileformat";
        private readonly ISqlSugarDbRepository _app;
        public FileUploadConfigService(ISqlSugarDbRepository app)
        {
            _app = app;
        }
        #region 获取数据
        /// <summary>
        /// 获取系统上传配置列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<FileUploadConfigEntity>> GetFileUploadConfigList()
        {
            try
            {
                var list = await GetList();
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 根据appid获取系统上传配置信息
        /// </summary>
        /// <param name="appid">系统appid</param>
        /// <returns></returns>
        public async Task<FileUploadConfigEntity> GetFileUploadConfigByAppId(string appid)
        {
            try
            {
                var list = await GetList();
                var entity = list.FirstOrDefault(t => t.appid == appid);
                return entity;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 根据主键获取系统上传配置信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<FileUploadConfigEntity> GetFileUploadConfigById(string id)
        {
            try
            {
                var list = await GetList();
                var entity = list.FirstOrDefault(t => t.id == id);
                return entity;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 常用格式支持
        /// </summary>
        /// <returns></returns>
        public async Task<List<FileFormatEntity>> GetFileFormatList()
        {
            try
            {

                var list = RedisCache.Read<List<FileFormatEntity>>(fileFormatCacheKey, CacheId.db0);
                if (list == null || list.Count == 0)
                {
                    list = await _app.GetListAsync<FileFormatEntity>();
                    RedisCache.Write(fileFormatCacheKey, list, CacheId.db0);
                }
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 获取系统上传配置列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<FileUploadConfigEntity>> GetList()
        {
            try
            {

                var list = RedisCache.Read<List<FileUploadConfigEntity>>(cacheKey, CacheId.db0);
                if (list == null || list.Count == 0)
                {
                    list = await _app.GetListAsync<FileUploadConfigEntity>();
                    RedisCache.Write(cacheKey, list, CacheId.db0);
                }
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        #endregion
        #region 数据提交
        /// <summary>
        /// 保存系统上传配置表单（新增、修改）
        /// </summary>
        /// <param name="req">系统上传配置输入实体</param>
        /// <returns></returns>
        public async Task<Response<bool>> SaveFileUploadConfigForm(SaveFileUploadConfigFormReq req)
        {
            try
            {
                var result = new Response<bool>();
                RedisCache.Remove(cacheKey, CacheId.db0);
                var entity = req.MapTo<FileUploadConfigEntity>();
                if (string.IsNullOrEmpty(entity.id))
                {
                    //查询是否在存在
                    var _entity = await _app.GetModelAsync<FileUploadConfigEntity>(t => t.appid == entity.appid);
                    if (_entity != null)
                    {
                        result.info = "该系统配置已存在";
                        result.data = false;
                        return result;
                    }
                    entity.id = Guid.NewGuid().ToString();
                    await _app.InsertAsync(entity);
                }
                else
                {
                    await _app.UpdateIgnoreColumnsAsync(entity);
                }
                result.data = true;
                return result;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 根据系统Appid删除系统上传配置信息
        /// </summary>
        /// <param name="appid">系统appid</param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteFileUploadConfigByAppId(string appid)
        {
            try
            {
                var result = new Response<bool>();
                var list = await GetList();
                var entity = list.FirstOrDefault(t => t.appid == appid);
                if (entity == null)
                {
                    result.info = "该系统配置不存在";
                    result.data = false;
                    return result;
                }
                //判断该系统下附上是否上传，如上传过，删除失败
                RedisCache.Remove(cacheKey, CacheId.db0);
                await _app.DeleteAsync<FileUploadConfigEntity>(t => t.appid == appid);
                result.data = true;
                return result;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 根据主键删除系统上传配置信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteFileUploadConfigById(string id)
        {
            try
            {
                var result = new Response<bool>();
                var list = await GetList();
                var entity = list.FirstOrDefault(t => t.id == id);
                if (entity == null)
                {
                    result.info = "该系统配置不存在";
                    result.data = false;
                    return result;
                }
                //判断该系统下附上是否上传，如上传过，删除失败
                RedisCache.Remove(cacheKey, CacheId.db0);
                await _app.DeleteAsync<FileUploadConfigEntity>(t => t.appid == id);
                result.data = true;
                return result;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        #endregion
    }
}
